<template>
    <div>
        <a-form layout="inline" :model="searchData" style="margin-top: 10px">
            <a-form-item>
                <a-input v-model:value="searchData.keyWord" placeholder="请输入"/>
            </a-form-item>
            <a-form-item>
                <a-tree-select
                        v-model:value="searchData.areaId"
                        show-search
                        style="width: 200px"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="Please select"
                        allow-clear
                        :tree-default-expand-all="false"
                        :tree-data="areaList"
                        :field-names="{label: 'name',value: 'id',children: 'children'}"
                />
            </a-form-item>
            <a-form-item>
                <a-space>
                    <a-button type="primary" @click="load(1)">搜索</a-button>
                    <a-button type="default" @click="reset">重置</a-button>
                </a-space>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-top: 10px" @click="openDrawModal({})">新增</a-button>
        <a-table :dataSource="officeList"
                 style="margin-top: 10px"
                 :columns="columns"
                 :pagination="false"
                 bordered>
            <template #type="{text,record}">
                {{text == 1 ? '国家' : '地方'}}
            </template>
            <template #action="{text,record}">
                <a-space>
                    <a-button type="primary" ghost @click="openQualification(record)" v-if="record.name != '新注册用户默认机构'">
                        申请资质
                    </a-button>
                    <a-button type="primary" v-if="record.name != '新注册用户默认机构'" @click="openDrawModal(record)">详情信息
                    </a-button>
                    <a-popconfirm
                            title="是否确认删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; float: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
        <a-drawer
                v-model:visible="drawVisible"
                class="custom-class"
                size="large"
                title="机构详情"
                placement="right"
        >
            <template #extra>
                <a-button type="primary" @click="handleOk">保存</a-button>
            </template>
            <a-form :model="office" style="margin-top: 10px" :label-col="{ span: 3 }">
                <a-form-item label="标题">
                    <a-input v-model:value="office.name"/>
                </a-form-item>
                <a-form-item label="地区">
                    <a-tree-select
                            v-model:value="office.areaId"
                            show-search
                            style="width: 200px"
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            placeholder="Please select"
                            allow-clear
                            :tree-default-expand-all="false"
                            :tree-data="areaList"
                            :field-names="{label: 'name',value: 'id',children: 'children'}"
                    />
                </a-form-item>
                <a-form-item label="具体地址">
                    <a-input v-model:value="office.address"/>
                </a-form-item>
                <a-form-item label="负责人">
                    <a-input v-model:value="office.master"/>
                </a-form-item>
                <a-form-item label="联系电话">
                    <a-input v-model:value="office.phone"/>
                </a-form-item>
            </a-form>
            <vue-ueditor-wrap v-model="office.remarks" :config="editorConfig"
                              editor-id="editor01"></vue-ueditor-wrap>
        </a-drawer>
        <a-drawer
                v-model:visible="visible"
                class="custom-class"
                size="large"
                title="资质申请"
                placement="right"
        >
            <a-form :model="qualification" :label-col="{ span: 3 }">
                <a-form-item label="机构名称">
                    <a-input v-model:value="office.name" :disabled="true"/>
                </a-form-item>
                <a-form-item label="资质类型">
                    <a-radio-group v-model:value="qualification.type">
                        <a-radio :disabled="office.roles.indexOf('1') == -1" :value="1">产废方</a-radio>
                        <a-radio :disabled="office.roles.indexOf('2') == -1" :value="2">运输方</a-radio>
                        <a-radio :disabled="office.roles.indexOf('3') == -1" :value="3">处置方</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="资质证书">
                    <a-upload
                            v-model:file-list="fileList"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            action="http://localhost:8086/upload/uploadAvatar"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                    >
                        <a-image v-if="imageUrl" :src="imageUrl" alt="avatar"
                                 style="width: 100px;height: 100px;"/>
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <a-form-item label="描述">
                    <a-textarea
                            v-model:value="qualification.description"
                            :auto-size="{ minRows: 2}"
                    />
                </a-form-item>
                <a-form-item>
                    <a-button style="margin-left: 80px" type="primary" @click="submitApplication">提交申请</a-button>
                </a-form-item>
            </a-form>
        </a-drawer>
    </div>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message} from 'ant-design-vue';
    import {LoadingOutlined, PlusOutlined} from '@ant-design/icons-vue'
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {arrayToTree} from "@/util/Tool";
    import cookies from 'js-cookie'

    export default {
        name: "system-office",
        components: {
            LoadingOutlined,
            PlusOutlined
        },
        setup() {
            const columns = [
                {
                    title: '机构名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '所在地区',
                    dataIndex: 'area',
                    key: 'area',
                    width: 100
                },
                {
                    title: '具体地址',
                    dataIndex: 'address',
                    key: 'address',
                },
                {
                    title: '负责人',
                    dataIndex: 'master',
                    key: 'master',
                    width: 100
                },
                {
                    title: '联系电话',
                    dataIndex: 'phone',
                    key: 'phone',
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center',
                    fixed: 'right',
                    width: '300px'
                }
            ]

            const loginUser = ref({})
            const locale = zhCN
            const office = ref({})
            const qualification = ref({})
            const officeList = ref([])
            const areaList = ref([])
            const searchData = ref({})
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
            const visible = ref(false);
            const drawVisible = ref(false);

            const fileList = ref([]);
            const loading = ref(false);
            const imageUrl = ref('');

            const handleChange = info => {
                if (info.file.status === 'uploading') {
                    console.log("上传uploading信息：", info)
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("上传done信息：", info)
                    imageUrl.value = info.file.response
                    loading.value = false
                }
                if (info.file.status === 'error') {
                    console.log("上传error信息：", info)
                    loading.value = false;
                    message.error('upload error');
                }
            };

            const beforeUpload = file => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isLt5M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt5M;
            };

            const handleOk = () => {
                axios.post('/sys-office/saveOrUpdate', office.value).then(rs => {
                    console.log("新增或修改结果：", rs)
                    if (rs.data.code == 200) {
                        drawVisible.value = false
                        message.success("操作成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const submitApplication = () => {
                qualification.value.officeId = office.value.id
                qualification.value.uploadUserId = loginUser.value.id
                qualification.value.address = imageUrl.value
                console.log("资质数据：", qualification.value)
                axios.post('qualificationProcess/startQualification', qualification.value).then(rs => {
                    if (rs.data.code == 200){
                        message.success("申请成功")
                        visible.value=false;
                    }else {
                        message.error(rs.data.message)
                    }
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/sys-office/delete/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const openQualification = (obj) => {
                console.log("模态框参数：", obj)
                office.value = JSON.parse(JSON.stringify(obj))
                qualification.value = {}
                if (office.value.roles.indexOf("1") != -1
                    && office.value.roles.indexOf("2") != -1
                    && office.value.roles.indexOf("3") != -1){
                    message.info("该机构已经拥有所有资质，无需申请")
                }else {
                    visible.value = true;
                }
            }
            const openDrawModal = (obj) => {
                console.log("模态框参数：", obj)
                drawVisible.value = true;
                office.value = JSON.parse(JSON.stringify(obj))
            }

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/sys-office/list', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        keyWord: searchData.value.keyWord,
                        areaId: searchData.value.areaId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    officeList.value = rs.data.data.records
                    pagination.value.total = rs.data.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const reset = () => {
                searchData.value = {}
                load()
            }

            const editorConfig = {
                UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
                serverUrl: 'http://localhost:8086/upload/uploadAvatar', // 服务端接口(文件上传)
                maximumWords: 100000
            };

            onMounted(() => {
                loginUser.value = JSON.parse(cookies.get('user'))
                // console.log("登录的用户", loginUser.value)
                axios.get('sys-area/queryAll').then(rs => {
                    areaList.value = arrayToTree(rs.data.data, 0)
                })
                load()
            })
            return {
                columns,
                office,
                officeList,
                pagination,
                pageSizeOptions,
                onChange,
                load,
                locale,
                searchData,
                reset,
                visible,
                handleOk,
                okDelete,
                areaList,
                editorConfig,
                drawVisible,
                openDrawModal,
                openQualification,
                qualification,
                fileList,
                loading,
                imageUrl,
                handleChange,
                beforeUpload,
                submitApplication
            }
        }
    }
</script>

<style scoped>

</style>